package com.atguigu.lease.common.qiniu;

import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@EnableConfigurationProperties(QiNiuProperties.class)
@org.springframework.context.annotation.Configuration
public class QiNiuConfig {

    @Autowired
    private QiNiuProperties qiNiuProperties;

    /**
     * 获取七牛云上传token
     *
     * @return
     */
    public String upload(MultipartFile file) throws IOException {
        //设置主机区域  华北
        Configuration cfg = new Configuration(Region.region1());
        //
        UploadManager uploadManager = new UploadManager(cfg);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");
        String key = String.join("/", simpleDateFormat.format(new Date()), file.getOriginalFilename());
        //唯一的时候用
        //String key = simpleDateFormat.format(new Date())+"/"+ UUID.randomUUID().toString().replace("-","")+"_"+file.getOriginalFilename();

        //鉴权 生成上传凭证uptoken
        Auth auth = Auth.create(qiNiuProperties.getAccessKey(), qiNiuProperties.getSecretKey());
        String upToken = auth.uploadToken(qiNiuProperties.getBucketName(),key);
        InputStream inputStream = file.getInputStream();
        Response response = uploadManager.put(inputStream, key, upToken, null, null);
        System.out.println("打印response========================" + response);
        String url = qiNiuProperties.getDomainOfBucket() + "/" + key;
        System.out.println("打印url========================" + url);
        return url;
    }

    public String delete(String url) throws QiniuException {
        if (url == null) {
            throw new RuntimeException("url不能为空");
        }
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.region1());
        String key = url.replace(qiNiuProperties.getDomainOfBucket() + "/", "");
        Auth auth = Auth.create(qiNiuProperties.getAccessKey(), qiNiuProperties.getSecretKey());
        BucketManager bucketManager = new BucketManager(auth, cfg);
        Response response = bucketManager.delete(qiNiuProperties.getBucketName(), key);
        String info = response.getInfo();
        System.out.println("打印info========================" + info);
        return "删除成功";
    }
}
